﻿
using System.Linq;
using System.Windows;
using Labthink.PCSoft.UniversalHost4.Model.Setting;
using Labthink.PCSoft.UniversalHost4.Utility;
using Newtonsoft.Json;

namespace Labthink.PCSoft.UniversalHost4.UserControls
{
    public partial class UcStorage
    {
        private NotifyManager _notify;
        public UcStorage()
        {
            InitializeComponent();
            BtnOk.Focus();
        }

        private async void BtnOk_OnClick(object sender, RoutedEventArgs e)
        {
            _triggerButtonsStatus(false);

            var di = new DiskInfo();
            di.Capacity = string.IsNullOrEmpty(TbSafeSpace.Value) ? 1024 : TbSafeSpace.Value.ToInt();
            di.AutoDelete = CbEnableAutoDel.IsChecked ?? false;
            di.Month = string.IsNullOrEmpty(TbMonthsForDel.Value) ? 3 : TbMonthsForDel.Value.ToInt();

            var sd = await Common.Instrument.Commands.SetDiskInfoAsync(di);

            _triggerButtonsStatus(true);

            if (sd.ErrorCode < 0)
            {
                //MessageBox.Show(sd.ErrorMsg);
                _notify.ShowError(sd.ErrorMsg);
            }
            else
            {
                _notify.ShowSuccess(sd.ErrorMsg);
            }
        }

        private void UcStorage_OnLoaded(object sender, RoutedEventArgs e)
        {
            var w = Window.GetWindow(this);
            _notify = NotifyManager.InstanceManager(w);

            LoadDiskInfo();
        }

        public string Title { get; set; } = LanguageManager.GetLanguageValue("StorageSetting");

        public string PermissionCode { get; set; } = "Per_StorageSetting";

        private async void LoadDiskInfo()
        {
            _triggerButtonsStatus(false);
            var sd = await Common.Instrument.Commands.GetDiskInfoAsync();
            _triggerButtonsStatus(true);
            if (sd.ErrorCode < 0)
            {
                //MessageBox.Show(sd.ErrorMsg);
                _notify.ShowError(sd.ErrorMsg);
            }
            else
            {
                var r = sd.Value;
                if (!string.IsNullOrEmpty(r))
                {
                    var diskInfo = JsonConvert.DeserializeObject<DiskInfo>(r);

                    TbSafeSpace.Value = diskInfo.Capacity + "";
                    CbEnableAutoDel.IsChecked = diskInfo.AutoDelete;
                    TbMonthsForDel.Value = diskInfo.Month + "";
                    TbLastScanTime.Value = diskInfo.Time.ToString("yyyy-MM-dd HH:mm");
                    TbTotalSpace.Value = diskInfo.Total.Round(1) + "";
                    TbUsedSpace.Value = diskInfo.Used.Round(1) + "";
                    TbFreeSpace.Value = diskInfo.Unused.Round(1) + "";
                }
            }
        }

        private void _triggerButtonsStatus(bool status)
        {
            BtnOk.IsEnabled = status;
            Loading.Visibility = status ? Visibility.Collapsed : Visibility.Visible;
        }
    }
}
